import {Component, OnInit, ViewChild} from '@angular/core';
import {LocalDataSource} from 'ng2-smart-table';
import {SmartTableData} from '../../@core/data/smart-table';
import {ActivatedRoute} from "@angular/router";
import {NbDateService, NbDialogService} from "@nebular/theme";
import {CommonFormDialog} from "../../utils/CommonFormDialog";
import {AdminService} from "../../AdminService";
import {BillService} from "../../energy/api";
import {BaseRequest} from "../../utils/BaseRequest";
import {UnitChargeBill} from "../../energy/api/model/unitChargeBill";
import {map} from "rxjs/operators";
import {ResponseUnitChargeBill} from "../../energy/api/model/responseUnitChargeBill";

@Component({
  selector: 'ngx-smart-table',
  templateUrl: './unit-bill.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }
    .margin {
      margin:10px;
    }
  `],
})
export class UnitBillComponent implements OnInit{
  settings = {
    pager:{
      display:true,
      perPage:20,
    },
    hideSubHeader: true,
    actions: {
      add:false,
      edit:false,
      delete: false,
      columnTitle: '操作',
      position: 'right',
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      confirmSave: true,
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      billNo: {
        title: '账单编号',
        type: 'string',
      },
      billType: {
        title: '账单类型',
        type: 'string',
      },
      unitId:{
        title: '单元ID',
        type: 'number'
      },
      grossArea: {
        title: '建筑面积',
        type: 'string',
      },
      netArea: {
        title: '有效面积',
        type: 'string',
      },
      // billDate: {
      //   title: '账单月',
      //   type: 'string',
      // },
      billCreateDate: {
        title: '出账日期',
        type: 'string',
      },
      billStartTime: {
        title: '开始计费',
        type: 'string',
      },
      billEndTime: {
        title: '停止计费',
        type: 'string',
      },
      billLimitDate: {
        title: '应缴截止日期',
        type: 'string',
      },
      totalConsumption: {
        title: '总结算用电量',
        type: 'string',
      },
      totalPooledAmt: {
        title: '公摊金额(总)',
        type: 'string',
      },
      amt: {
        title: '金额',
        type: 'string',
      },
      totalAmt: {
        title: '结算金额',
        type: 'string',
      },
      billStatus: {
        title: '账单状态',
        type: 'string',
      },
      extInfo: {
        title: '额外信息',
        type: 'string',
      },
    },
  };
  source: DataDataSource;
  maxPage:number = 1;
  page:number = 1;
  limit:number = 25;
  unitId?:number=null;
  startTime:Date;
  endTime:Date;
  billNo:string;
  billType: string;
  billStatus:string;
  @ViewChild('dialog') dialog;
  constructor(private service: SmartTableData
              ,private api:BillService
              ,private route:ActivatedRoute
              ,private dateService: NbDateService<Date>
              ,private dialogService:NbDialogService
              ,private admin:AdminService) {
    this.startTime = this.dateService.addDay(this.dateService.today(), -30);
    this.endTime = this.dateService.today()
  }

  ngOnInit(): void {
    this.route.paramMap.subscribe(value=>{
      const unitId =  value.get('unitId');
      if(unitId!=null)
        this.unitId = Number(unitId);
      this.source = new DataDataSource(this.api,this.dateService,this.startTime,this.endTime,this.billNo,this.billType,this.billStatus,this.unitId);
    });

  }

  filter(){
    if(this.unitId!=null)
      this.source.unitId = this.unitId;
    if(this.startTime!=null)
      this.source.startTime = this.startTime;
    if(this.endTime!=null)
      this.source.endTime = this.endTime;
    if(this.billNo!=null)
      this.source.billNo = this.billNo;
    if(this.billType!=null)
      this.source.billType = this.billType;
    if(this.billStatus!=null)
      this.source.billStatus = this.billStatus;
    this.source.setPage(1);
    this.source.refresh();
  }

  openPayPrompt(){
    this.dialogService.open(this.dialog).onClose.subscribe(v=>{
      if(v==null) return;
      this.api.postECASyncBillResult(new BaseRequest(v)).toPromise().then(response=>{
        console.log(response);
      })
    });
  }

  openAddPrompt(){
    const keys = Object.keys(this.settings.columns).filter(k => {
      return (this.settings.columns[k]['type'] == 'string' || this.settings.columns[k]['type'] == 'number')
    });
    const columns = keys.map(k => {
      const tmp = this.settings.columns[k];
      if(k.endsWith("Date")) tmp['custom']="date";
      return tmp;
    });
    this.dialogService.open(CommonFormDialog,{
      context:{
        data:columns,
        title: '账单录入'
      }
    }).onClose.subscribe(results=>{
      if(results==null) return;
      const data = <UnitChargeBill>{};
      keys.forEach((k, i) => {
        if (columns[i]['type'] == 'number') {
          data[k] = Number(results[i]);
        } else {
          data[k] = results[i];
        }
      });
      this.api.postECAUnitChargeBill(new BaseRequest([data])).toPromise().then(response => {
        console.log(response);
        this.source.refresh();
      })
    })
  }

}

export class DataDataSource extends LocalDataSource {
  all: number = -1;
  constructor(private api: BillService,private dateService: NbDateService<Date>,public startTime:Date,public endTime:Date,public billNo:string,public billType:string,public billStatus:string,public unitId?:number) {
    super()
  }

  count(): number {
    return this.all;
  }

  getElements(): Promise<any> {
    const query = {
      pageIndex: (this.pagingConf['page'] - 1) * this.pagingConf['perPage'],
      pageSize: this.pagingConf['perPage'],
      startTime:this.dateService.format(this.startTime,"yyyyMMdd"),
      endTime:this.dateService.format(this.endTime,'yyyyMMdd')
    };
    if(this.unitId!=null) query['unitId']=this.unitId;
    if(this.billNo!=null) query['billNo'] = this.billNo;
    if(this.billType!=null) query['billType'] = this.billType;
    if(this.billStatus!=null) query['billStatus'] = this.billStatus;
    return this.api.requestECAUnitChargeBill(new BaseRequest(query)).pipe(map((res:ResponseUnitChargeBill)=>{
      this.all = res.dataCount;
      return res.data;
    })).toPromise();
  }
}
